<template>
  <div @click="indexNum = -1">
    <div class="major" style="margin-top: 30px">
      <div class="major-left">职业选择</div>
      <div class="major-right">
        <el-popover
          v-for="(item, index) in jobList"
          :key="index"
          :visible="indexNum == index"
          placement="bottom"
          width="auto"
          trigger="click"
        >
          <template #reference>
            <div
              class="major-size alitem"
              :class="indexNum === index ? 'active' : ''"
              @click.stop="clickChange(index)"
            >
              <div>{{ item.name }}({{ item.children.length }})&nbsp;</div>
              <el-icon>
                <ArrowDown />
              </el-icon>
            </div>
          </template>
          <el-checkbox-group
            v-model="tempSelJobs"
            style="display: flex; flex-wrap: wrap; width: 500px"
          >
            <el-checkbox
              v-for="job in item.children"
              :key="job"
              :value="job"
              @change="handleCheckedCitiesChange"
              >{{ job.name }}</el-checkbox
            >
          </el-checkbox-group>
          <div class="right matop">
            <el-button @click="indexNum = -1">取消</el-button>
            <el-button type="primary" @click="onClickCheckboxConfirm"
              >确定</el-button
            >
          </div>
        </el-popover>
      </div>
    </div>
    <el-row class="matop" @click="handleIsShowNoVip">
      <el-col :span="12">
        <div class="alitem">
          <div class="major-left">意向专业</div>
          <el-input
            ref="buttonRef"
            v-model="searchKey"
            style="width: 240px"
            placeholder="输入意向职业"
            clearable
            @input="searchKeyInput"
            @focus="isShowSearchPop = true"
            @blur="isShowSearchPop = false"
          >
            <template #prefix>
              <el-icon class="el-input__icon">
                <search />
              </el-icon>
            </template>
          </el-input>
          <div style="margin: 0 6px 0 20px">
            <el-checkbox
              v-model="isAllchecked"
              :label="`用户关注(${careerData.length})`"
              size="large"
              @change="toggleAll"
            />
          </div>
          <div style="margin-top: 4px">
            <el-popover
              :visible="visible"
              ref="myPopover"
              placement="bottom"
              :width="180"
              v-model:visible="showPopover"
            >
              <span v-if="careerData.length == 0">暂无关注的意向专业...</span>
              <div
                style="display: flex; flex-direction: column"
                v-for="(item, index) in careerData"
                :key="index"
              >
                <el-checkbox-group v-model="Cities.checkedCities">
                  <el-checkbox
                    @change="changeItem"
                    :value="item"
                    :label="item.jobName"
                    size="large"
                  />
                </el-checkbox-group>
              </div>

              <div
                style="display: flex; justify-content: flex-end"
                v-if="careerData.length != 0"
              >
                <el-button type="primary" size="small" @mousedown="schoolSubmit"
                  >确定</el-button
                >
              </div>

              <template #reference>
                <el-icon
                  @click="visible = !visible"
                  class="el-icon--right"
                  size="16"
                >
                  <ArrowDown />
                </el-icon>
              </template>
            </el-popover>
          </div>
          <div
            v-show="isShowSearchPop && searchList.length > 0"
            class="search-popover"
          >
            <div
              class="curr"
              v-for="(item, index) in searchList"
              :key="index"
              @mousedown="onClickSearchItem(item, index)"
            >
              <div style="padding: 5px 0">
                {{ index == 0 ? '在筛选条件中搜索 "' + item + '"' : item.name }}
              </div>
              <div
                v-if="index + 1 < searchList.length"
                style="width: 100%; height: 1px; background-color: #eee"
              ></div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
  <novip ref="novipRef" />
</template>
<script setup>
import { ref, reactive } from 'vue';
import { allCareer, searchCareer } from '@/api/volunteer/volunteer.js';
// import userSearch from "@/store/modules/searchInfo.js";
import novip from '@/components/NoVip';

import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';
import _ from 'lodash';
const novipRef = ref(null);
// const userSearchVal = userSearch()
const store = useStore();

const indexNum = ref(-1);

const searchList = ref([]); // 模糊搜索数据源
const jobList = ref([]); // 职业筛选数据源
const selJobs = ref([]); // 选中的职业筛选数据
const tempSelJobs = ref([]); // 临时模糊搜索数据
const searchKey = ref(''); // 搜索关键词
const isShowSearchPop = ref(false); // 是否显示搜索pop
const isAllchecked = ref(false);
const visible = ref(false);
// const schoolList = ref([]);
const showPopover = ref(false);
const Cities = reactive({
  checkedCities: [],
});

const props = defineProps({
  // 批次线信息
  careerData: {
    type: Array,
    default: () => [],
  },
});
// 模糊搜索
const searchItem = reactive({
  code: 0,
  name: '',
  type: 'zsearch',
});
const handleIsShowNoVip = () => {
  if (store.getters.user.userInfo.isVIP == 0) {
    novipRef.value.handleIsShowDialog();
  }
};
function getallJob() {
  // console.log('----', props.batchInfo)
  allCareer({}).then((res) => {
    jobList.value = res.data.data;

    // 一键填报数据回显处理
    if (Number(localStorage.getItem('isYJTB')) == 1) {
      // 获取本地存储的职业筛选数据
      let selArr = JSON.parse(localStorage.getItem('jobArrayList')) || [];

      // 循环遍历本地数据和服务器数据code是否相同，相同添加到已选中数组
      selArr.forEach((item) => {
        jobList.value.forEach((job) => {
          const data = job.children.filter((i) => i.code == item.code);

          if (data.length > 0) {
            selJobs.value.push(data[0]);
          }
        });
      });
    }
  });
}
getallJob();

// 搜索输入值改变
const searchKeyInput = _.throttle((val) => {
  if (val.length >= 2) {
    searchCareer({
      search: val,
      pageSize: 1000,
    }).then((res) => {
      // console.log('--res--', res)
      searchList.value = res.data.data;

      searchList.value.splice(0, 0, searchKey.value);
      isShowSearchPop.value = true;
    });
  } else {
    searchList.value = [];
    isShowSearchPop.value = false;
  }
}, 800);

// 点击单个筛选专业
const handleCheckedCitiesChange = () => {
  // console.log('选中的数据信息', value)
  if (tempSelJobs.value.length > 5) {
    tempSelJobs.value.splice(5, 1);

    ElMessage({
      message: '意向职业不得超过5个！',
      type: 'warning',
    });
  }
};

/**
 * 点击专业组
 * @param {Number} val 专业组下标
 */
function clickChange(val) {
  if (store.getters.user.userInfo.isVIP != 0) {
    if (indexNum.value == val) {
      indexNum.value = -1;
    } else {
      indexNum.value = val;
    }
    // console.log(selJobs.value)
    tempSelJobs.value = JSON.parse(JSON.stringify(selJobs.value));
  } else {
    novipRef.value.handleIsShowDialog();
  }
}

// 确定筛选条件
function onClickCheckboxConfirm() {
  selJobs.value = tempSelJobs.value;
  indexNum.value = -1;

  saveJobInfo();
}

/**
 * 点击搜素选项
 * @param {Object} item 专业数据
 * @param {Number} index 下标
 */
function onClickSearchItem(item, index) {
  if (index == 0) {
    // 模糊搜索
    searchItem.name = item;
    saveJobInfo();
  } else {
    if (selJobs.value.length >= 5) {
      ElMessage({
        message: '意向职业不得超过5个！',
        type: 'warning',
      });
    }

    // 精准专业搜索
    let index = selJobs.value.findIndex((i) => i.code == item.code);
    if (index < 0) {
      selJobs.value.push(item);
      saveJobInfo();
    }
  }

  // 添加后清除搜索数据
  searchKey.value = '';
  searchList.value = [];
  isShowSearchPop.value = false;
}
const schoolSubmit = () => {
  if (Cities.checkedCities.length !== props.careerData.length) {
    isAllchecked.value = false;
  }
  if (Cities.checkedCities.length > 0) {
    Cities.checkedCities.forEach((item) => {
      const selectedItem = {
        code: item.code,
        name: item.jobName,
        type: 'job',
      };
      let index = selJobs.value.findIndex((i) => i.code == item.code);
      if (index < 0) {
        selJobs.value.push(selectedItem);
        store.dispatch('tianbao/saveJobInfoChange', selJobs.value);
      }
    });
  }
  visible.value = false;
};
const changeItem = () => {
  isAllchecked.value = Cities.checkedCities.length === props.careerData.length;
};
const toggleAll = (val) => {
  // searchArray.value = [];
  if (val) {
    // 全选操作
    if (props.careerData.length) {
      props.careerData.forEach((v) => {
        v.isChange = true; // 标记为已选
        if (!Cities.checkedCities.includes(v.code)) {
          Cities.checkedCities.push(v);
        }
      });
    }

    // 将选中的项存储到 selItemArray
    if (Cities.checkedCities.length > 0) {
      Cities.checkedCities.forEach((itemCode) => {
        const selectedItem = props.careerData.find(
          (item) => item.code === itemCode.code,
        );
        if (selectedItem) {
          const searchArray = {
            code: selectedItem.code,
            name: selectedItem.jobName,
            type: 'job',
          };
          let index = selJobs.value.findIndex(
            (i) => i.code == selectedItem.code,
          );
          if (index < 0) {
            selJobs.value.push(searchArray);
            store.dispatch('tianbao/saveJobInfoChange', selJobs.value);
          }
        }
      });
    }
  } else {
    // 取消全选操作
    props.careerData.forEach((v) => {
      v.isChange = false; // 标记为未选
      const index = Cities.checkedCities.indexOf(v);
      if (index !== -1) {
        Cities.checkedCities.splice(index, 1); // 移除已选项
      }
    });
    // 如果取消全选，清空 selItemArray
    selJobs.value = [];
    store.dispatch('tianbao/saveJobInfoChange', selJobs.value);
  }
  visible.value = false;
};
// 保存专业筛选数据到仓库
function saveJobInfo() {
  let searchArray = [];
  selJobs.value.forEach((item) => {
    searchArray.push({
      name: item.name,
      code: item.code,
      type: 'job',
    });
  });

  // 判断是否存在模糊搜索
  if (searchItem.name.length > 0) {
    searchArray.push(searchItem);
  }

  // userSearchVal.saveJobInfoChange(searchArray); // 保存到 store 中
  store.dispatch('tianbao/saveJobInfoChange', searchArray);
}

/**
 * 删除某条筛选条件
 * @param {Object} item {type:'类型', code:'id', name:'标题'}
 */
function deleteScreenItem(item) {
  if (item.type == searchItem.type) {
    searchItem.name = '';
  } else {
    selJobs.value = selJobs.value.filter((i) => i.code != item.code);
  }
  saveJobInfo();
}

function deleteAll() {
  selJobs.value = [];
  tempSelJobs.value = [];
  searchItem.name = '';
  saveJobInfo();
}
function closeV() {
  visible.value = false;
}
defineExpose({
  deleteScreenItem,
  deleteAll,
  closeV,
});
</script>
<style lang="scss" scoped>
.flexend {
  div {
    font-size: 14px;
    font-weight: 400;
    color: #4e5969;
    line-height: 14px;
    margin-right: 20px;
  }
}
.major-left {
  width: 100px;
  font-size: 14px;
  text-align: center;
  color: #9b9b9b;
}
.major {
  display: flex;
  margin-top: 10px;

  .major-right {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .major-size {
      font-size: 14px;
      margin-bottom: 12px;
      padding: 4px 16px;
      margin-right: 10px;
      text-align: center;
      border: 1px solid #e5e6eb;
      border-radius: 4px;
      cursor: pointer;
      color: #4e5969;
    }

    .active {
      border: 1px solid #004cf7;
      color: #004cf7;
    }
  }
}

.search-popover {
  position: absolute;
  top: 40px;
  left: 15px;
  width: 240px;
  height: 200px;
  overflow: auto;
  background-color: white;
  z-index: 999;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  border: 1px solid #c9cdd4;
  padding: 0 10px;
  font-size: 14px;
}
</style>
